﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text.RegularExpressions;


namespace CCPSIP.vCardGE
{
    /// <summary>【Dev】CCPSIP_059：群組名片交換 - 完成交換 API</summary>
    /// idHeader = 裝置 UUID 前八碼。
    /// checkcode = 裝置限時驗證碼。
    /// VGEKey = 群組名片交換Key string。
    /// ConfirmList = 確認交換名單，成員間以 "," 分隔。例如 "88953,88983,88239"。

    public class finish : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string VGEKey = req.Form["VGEKey"];//群組名片交換Key string
                string ConfirmList = req.Form["ConfirmList"];//確認交換名單

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }


                //【02】檢查此交換是否等待完成
                //
                bool isWaiting = OracleKitVCardGE.hasWaitingVGE(VGEKey);
                if (!isWaiting)
                {
                    throw new Exception("Error_02: VGE not found or expired");//找不到此交換
                }


                //【03】檢查是否為交換群組Host
                //
                bool isHost = OracleKitVCardGE.isHost(VGEKey, userInfo.SIP_Num);
                if (!isHost)
                {
                    throw new Exception("Error_03: You are not the Host of the VGE");//不是交換群組Host
                }


                //【04】過濾確認名單
                //
                List<string> finalList = new List<string>();
                foreach (string cMember in ConfirmList.Split(','))
                {
                    if (Regex.IsMatch(cMember, SipKit.kSIPNumPattern))
                        finalList.Add(cMember);
                }


                //【05】完成交換動作
                //
                OracleKitVCardGE.FinishVCardGE(VGEKey, finalList.ToArray());


                //【98】通知Push Service
                //
                PushKit.WakePushAsync(PushKit.PushType.Msg);


                //【99】回傳結果
                //
                resultStr = "OK";
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
